<template>
  <div class="app-container">
  <!--还没好-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="城市" prop="city">
       <el-select v-model="queryParams.city" placeholder="请选择" clearable filterable size="small" @keyup.enter.native="handleQuery" >
         <el-option
           v-for="dict in ownCity"
           :key="dict.value"
           :label="dict.label"
           :value="dict.label"
         />
       </el-select>
      </el-form-item>
      <el-form-item label="选择校区" prop="schoolId">
       <el-select v-model="queryParams.schoolId" placeholder="请选择" clearable filterable size="small" @keyup.enter.native="handleQuery" >
         <el-option
           v-for="dict in schoolOptions"
           :key="dict.value"
           :label="dict.name"
           :value="dict.id"
         />
       </el-select>
      </el-form-item>
      <el-form-item label="站点名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          size="small"
        >
          <el-option :key="999" :label="'全部'" :value="null" />
           <el-option :key="0" :label="'启用'" :value="0" />
           <el-option :key="1" :label="'关闭'" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:site:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:site:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:site:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:site:export']"
        >导出</el-button> -->
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点名称" align="center" prop="name" />
      <el-table-column label="所属校区" align="center" prop="schoolName" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <div class="dian" :class="scope.row.status === 1 ? '':'bg-success'" ></div><span>{{scope.row.status === 1?'关闭':'启用'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="insertOperator" />
      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row, '详情')"
            v-hasPermi="['system:site:details']"
          >查看</el-button>
          <el-button
            size="mini"
            type="success"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:site:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:site:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="选择校区" prop="schoolId">
              <el-select v-model="form.schoolId" placeholder="请选择" clearable filterable size="small" @change="selectSchool" >
                <el-option
                  v-for="dict in schoolOptions"
                  :key="dict.value"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <div style="color: #46A6FF;padding-left: 120px;margin-bottom: 10px;cursor: pointer;" @click="mapOpenHandle">
              地图选点
            </div>
            <el-form-item label="">
              <el-col :span="11">
                <el-form-item label="经度" label-width="40px" prop="lon">
                  <el-input v-model="form.lon" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="2">&nbsp;</el-col>
              <el-col :span="11">
                <el-form-item label="纬度" label-width="40px" prop="lat">
                  <el-input v-model="form.lat" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>

          <el-col :span="18">
            <el-form-item label="是否启用" prop="status">
              <el-switch
                v-model="form.status"
                :active-value="0"
                :inactive-value="1"
              />
            </el-form-item>
          </el-col>

          <el-col :span="18">
            <el-form-item label="站点描述" prop="siteDescribe">
              <el-input v-model="form.siteDescribe" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点负责人" prop="personInCharge">
              <el-input v-model="form.personInCharge" placeholder="请输入" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="负责人电话">
              <el-input v-model="form.mobile" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点负责人2" prop="personInCharge2">
              <el-input v-model="form.personInCharge2" placeholder="请输入用户密码" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="负责人2电话">
              <el-input v-model="form.mobile2" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="有效期" prop="time">
              <el-date-picker
                v-model="form.time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详细 -->
    <el-dialog title="详细" :visible.sync="detailOpen" width="600px">
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="18">
            <el-form-item label="所属校区：">{{ form.schoolName }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="所在城市：">{{ form.city }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点名称：">{{ form.name }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点详细地址：">{{ form.address }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="状态：">
              <div v-if="form.status === 1">关闭</div>
              <div v-else-if="form.status === 0">启用</div>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点描述：">{{ form.siteDescribe }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点负责人：">{{ form.personInCharge }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="负责人电话：">{{ form.mobile }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="站点负责人2：">{{ form.personInCharge2 }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="负责人2电话：">{{ form.mobile2 }}</el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="有效期：">{{ form.startTime + ' 至 ' +  form.endTime }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 详细 -->
    <el-dialog title="地图" :visible.sync="mapOpen" width="800px">
      <div style="margin-bottom: 50px;">
        <gdMap @chind-list="setInputList" :defaultPoint="defaultPoint"></gdMap>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confimMap">确 认</el-button>
        <el-button @click="mapOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportUser } from "@/api/system/user";
import { listSite,addSite,delSite } from "@/api/pt/site.js";
import { listSchool } from "@/api/pt/school.js";
import { getToken } from "@/utils/auth";
import { areajson } from "@/utils/area.js";
import gdMap from '@/components/gd-map'

export default {
  name: "User",
  components: {
    gdMap
  },
  data() {
    return {
      mapOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      tableList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 已有校区所在城市数据
      ownCity: [],
      // 已有校区数据
      schoolOptions: [],
      // 城市数据
      cityOptions: areajson,
      // 表单参数
      form: {},
      /* 地图选点暂存数据 */
      formMap:{},
      // 地图编辑选点回显
      defaultPoint:{},
      //详情打开
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        schoolId: undefined,
        city: undefined,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "站点名称不能为空", trigger: "blur" }
        ],
        schoolId: [
          { required: true, message: "请选择校区", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        time: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();

    listSchool({status:0,pageNum: 1,pageSize: 10000}).then(response => {
      let list = response.data.list
      let lArr = ''
      let listArr = []
      list.map(item=>{
        if(lArr.indexOf(item.city) == -1) {
          lArr += ',' + item.city
        }
      })
      lArr = lArr.split(',')
      lArr.map(item=>{
        listArr.push({
          label: item ? item : '全部',
          value: item
        })
      })
      this.schoolOptions = response.data.list
      this.ownCity = listArr
    });
  },
  methods: {
    mapOpenHandle(){
      this.mapOpen = true
      this.defaultPoint= {
        lon: this.form.lon,
        lat: this.form.lat,
        address: this.form.address,
      }
    },
    /* 确认地图选点设置经纬度*/
    confimMap(){
      this.form.lon = this.formMap.lng
      this.form.lat = this.formMap.lat
      this.mapOpen = false
    },
    /* 地图选点信息*/
    setInputList(address,lng,lat){
      console.log(123)
      console.log(address[0])
      this.formMap = address[0];
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listSite(this.addDateRange2(this.queryParams)).then(response => {
          this.tableList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status === 0 ? "启用" : "关闭";
      this.$confirm('确认要' + text + '"' + row.name + '"吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          row.time = [new Date(row.startTime),new Date(row.endTime)]
          return addSchool(row)
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
      this.form = {
        id: undefined,
        schoolId: undefined,
        name: undefined,
        city: undefined,
        status: undefined,
        address: undefined,
        siteDescribe: undefined,
        personInCharge: undefined,
        mobile: undefined,
        personInCharge2: undefined,
        mobile2: undefined,
        time: undefined,
        lon: undefined,
        lat: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      console.log(row)
      this.title = "修改";
      row.time = [new Date(row.startTime),new Date(row.endTime)]
      this.form = JSON.parse(JSON.stringify(row))
      if(type === '详情') {
        this.detailOpen = true;
      }else {
        this.open = true;
      }
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.time){
            this.form.startTime =  this.parseTime(this.form.time[0])
            this.form.endTime =  this.parseTime(this.form.time[1], '{y}-{m}-{d} {23}:{59}:{59}')
          }
          delete this.form.time
          if (this.form.id !== undefined) {
            addSite(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          } else {
            this.form.id = undefined
            addSite(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      this.$confirm('是否确认删除站点ID为"' + Ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSite(Ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.fileDownload(response.data, "用户管理.xlsx");
        }).catch(function() {});
    },

    // 获取当前选中校区所在城市
    selectSchool(val) {
      this.schoolOptions.map(item=>{
        if(item.id === val) this.form.city = item.city
      })
    }
  }
};
</script>

<style type="text/css">
  .dian {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    display: inline-block;
    background: #999;
    margin-right: 6px;
  }
</style>
